package com.yonyou.service;

import com.yonyou.dao.LoginDao;
import com.yonyou.exception.ErrorMessageException;
import com.yonyou.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author wangchu
 * @date 2025-08-10 11:04
 */
@Slf4j
@Service
public class LoginService {

    @Autowired
    private LoginDao loginDao;

    /**
     * 登录方法
     */
    public LoginUser login(LoginUser user) {
        LoginUser loginUser = loginDao.login(user);
        if (Objects.isNull(loginUser)) {
            throw new ErrorMessageException("登录失败！");
        }
        String expectMac = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(loginUser.getPassword().getBytes(StandardCharsets.UTF_8)) + user.getTs()).getBytes(StandardCharsets.UTF_8));
        if (!expectMac.equals(user.getPassword())) {
            throw new ErrorMessageException("用户名或密码错误！");
        }
        loginUser.setPassword(null);
        return loginUser;
    }
}